import User.MessageDTO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;


@WebServlet("/UploadServlet")
@MultipartConfig(location = "F:\\javaEE\\IdeaProjects\\exp3\\src\\main\\webapp\\images")// location改为本地的绝对路径
public class UploadServlet extends HttpServlet {
    //更新头像
    protected static void UploadImg(MessageDTO message)
    {
        String line=null;
        String s1=null;
        StringBuilder stringBuilder=new StringBuilder();
        try{
            BufferedReader bufferedReader=new BufferedReader(new FileReader(("src/main/user.txt")));
            while((line=bufferedReader.readLine())!=null)
            {
                String[] str = line.split(" ");
                if (message.getname().equals(str[0])&&!message.getimg().equals(str[4])) {
                    s1=message.getname()+" "+message.gete_mail()+" "+message.getpassword()+" "+message.getPhone()+" "+message.getimg();
                }
                else s1=line;
                stringBuilder.append(s1);
                stringBuilder.append("&");
            }
            bufferedReader.close();
            String s2=stringBuilder.toString();
            String string[]=s2.split("&");
            BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("src/main/user.txt"));
            for(int i=0;i<string.length;i++)
            {
                bufferedWriter.write(string[i]);
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } catch (IOException e) {
            System.out.println("上传头像信息失败！");
        }

    }


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取请求项，封装成Part对象
        // request.getPart方法的传参为前端页面from表单的input文件组件的name值
        Part part = request.getPart("picture");
        if(part==null){
            System.out.println(part);
            return;
        }

        // part.getSubmittedFileName()方法获取上传文件的文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("上传文件的文件名: " + fileName);

        // 根据@MultipartConfig的location配置的目录上传文件，直接传参文件名即可。
        part.write(fileName);

        response.getWriter().write("文件上传成功！");


        MessageDTO messageDTO=(MessageDTO)request.getSession().getAttribute("LocalUser");
        messageDTO.setimg(fileName);
        request.getSession().setAttribute("LocalUser",messageDTO);
        UploadImg(messageDTO);
        response.sendRedirect("show.jsp");

    }
}